package com.ruoyi.psi.sale.delivery.service;


import com.ruoyi.DingDing.Domain.DingDingText;
import com.ruoyi.constant.ERPConstant;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.personnel.oa.approve.domain.ApproveDomain;
import com.ruoyi.personnel.oa.approve.mapper.ApproveMapper;
import com.ruoyi.personnel.oa.sequence.service.IApproveSequenceService;
import com.ruoyi.psi.base.product.domain.ProductDto;
import com.ruoyi.psi.base.product.service.IProductService;
import com.ruoyi.psi.inventory.record.domain.StockInRecord;
import com.ruoyi.psi.inventory.record.mapper.StockInRecordMapper;
import com.ruoyi.psi.inventory.recordOut.domain.StockOutRecord;
import com.ruoyi.psi.inventory.recordOut.service.IStockOutRecordService;
import com.ruoyi.psi.sale.delivery.domain.*;
import com.ruoyi.psi.sale.delivery.mapper.SaleDeliveryMapper;
import com.ruoyi.psi.sale.order.domain.SaleOrderListDto;
import com.ruoyi.psi.sale.order.mapper.SaleOrderMapper;
import com.ruoyi.psi.sale.order.service.ISaleOrderService;
import com.ruoyi.utils.ID.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 销售出库
 * 业务执行层
 */
@Service
public class SaleDeliveryServiceImpl implements ISaleDeliveryService {
    @Autowired
    private SaleDeliveryMapper saleDeliveryMapper;
    @Autowired
    private SaleOrderMapper saleOrderMapper;
    @Autowired
    private ISaleOrderService saleOrderService;
    @Autowired
    private IProductService productService; //产品信息
    @Autowired
    private StockInRecordMapper stockInRecordMapper;
    @Autowired
    private IStockOutRecordService stockOutRecordService;
    @Autowired
    private IApproveSequenceService approveSequenceService;
    @Autowired
    private ApproveMapper approveMapper;
    @Autowired
    private IdUtil idUtil;

    /**
     * 销售订单出库查询
     *
     * @param cond
     * @return
     */
    @Override
    public List<SaleDeliveryDto> selectSaleDeliveryList(SaleDeliveryCond cond) {
        List<SaleDeliveryDto> saleDeliveryDtos = saleDeliveryMapper.selectSaleDeliveryList(cond);
        for (SaleDeliveryDto s : saleDeliveryDtos) {
            double saleDeliveryNumberTotal = 0.00; //出库总数
            double saleDeliveryPriceTotal = 0.00; //出库总价
            if (StringUtils.isNotNull(saleDeliveryMapper.selectSaleDeliveryListListById(s.getSaleDeliveryId()))) {
                //存在，则存入销售订单出库对应产品信息
                List<SaleDeliveryListDto> saleDeliveryListDtos = saleDeliveryMapper.selectSaleDeliveryListListById(s.getSaleDeliveryId());
                for (SaleDeliveryListDto sl : saleDeliveryListDtos) {
                    saleDeliveryNumberTotal += sl.getSaleDeliveryNumber();
                    saleDeliveryPriceTotal += sl.getSaleDeliveryUnitPrice() * sl.getSaleDeliveryNumber();
                }
                s.setSaleDeliveryLists(saleDeliveryListDtos);
            }
            s.setSaleDeliveryNumberTotal(saleDeliveryNumberTotal);
            s.setSaleDeliveryPriceTotal(saleDeliveryPriceTotal);
        }
        return saleDeliveryDtos;
    }

    /**
     * 按编号查询
     *
     * @param saleDeliveryId 销售订单出库编号
     * @return
     */
    @Override
    public SaleDeliveryDto selectSaleDeliveryById(String saleDeliveryId) {
        SaleDeliveryDto saleDeliveryDto = saleDeliveryMapper.selectSaleDeliveryById(saleDeliveryId);
        double saleDeliveryNumberTotal = 0.00; //出库总数
        double saleDeliveryPriceTotal = 0.00; //出库总价
        if (StringUtils.isNotNull(saleDeliveryMapper.selectSaleDeliveryListListById(saleDeliveryDto.getSaleDeliveryId()))) {
            //存在，则存入销售订单出库对应产品信息
            List<SaleDeliveryListDto> saleDeliveryListDtos = saleDeliveryMapper.selectSaleDeliveryListListById(saleDeliveryDto.getSaleDeliveryId());
            for (SaleDeliveryListDto sl : saleDeliveryListDtos) {
                saleDeliveryNumberTotal += sl.getSaleDeliveryNumber();
                saleDeliveryPriceTotal += sl.getSaleDeliveryUnitPrice() * sl.getSaleDeliveryNumber();
            }
            saleDeliveryDto.setSaleDeliveryLists(saleDeliveryListDtos);
        }
        saleDeliveryDto.setSaleDeliveryNumberTotal(saleDeliveryNumberTotal);
        saleDeliveryDto.setSaleDeliveryPriceTotal(saleDeliveryPriceTotal);
        return saleDeliveryDto;
    }

    /**
     * 销售订单出库新增
     *
     * @param saleDelivery 销售出库单据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertSaleDelivery(SaleDeliveryDomain saleDelivery) throws Exception {
        String saleDeliveryId = idUtil.createSaleDeliveryId();//自动生成编号
        if (StringUtils.isNotNull(saleDeliveryMapper.selectSaleDeliveryById(saleDeliveryId))) {
            //存在
            return 0;
        }
        //不存在
        saleDelivery.setSaleDeliveryId(saleDeliveryId); // 主表添加编号

        ApproveDomain approve = new ApproveDomain(saleDeliveryId, "销售出库审批", ERPConstant.APPROVAL_TYPE_SALE_DELIVERY, saleDelivery.getStaffId()); //新增审批
        approve.setCurrentApprover(approveSequenceService.getLowestRoleId(ERPConstant.APPROVAL_TYPE_SALE_DELIVERY));
        approveMapper.insertApprove(approve);
        Long currentApprover = approve.getCurrentApprover();
        DingDingText dingDingText = new DingDingText();
        dingDingText.BatchRobotText(currentApprover);

        saleDeliveryMapper.insertSaleDelivery(saleDelivery);//销售订单出库据

        saleOrderMapper.updateActualDeliveryTime(saleDelivery.getSaleOrderId()); //更新该销售订单销售出库的时间
        saleOrderMapper.updateSaleOrderDeliveryStatus(saleDelivery.getSaleOrderId()); //更新该销售订单销售出库情况为出库

        List<SaleDeliveryListDomain> saleDeliveryListDomainList = saleDelivery.getSaleDeliveryLists();//销售订单出库产品信息
        for (int i = 0; i < saleDeliveryListDomainList.size(); i++) {
            saleDeliveryListDomainList.get(i).setSaleDeliveryId(saleDeliveryId);// 子表添加编号
            saleDeliveryMapper.insertSaleDeliveryList(saleDeliveryListDomainList.get(i));//销售订单出库产品信息
        }
        return 1;
    }

    /**
     * 销售订单出库更新
     *
     * @param saleDelivery 销售出库单据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSaleDelivery(SaleDeliveryDomain saleDelivery) throws Exception {
        if (!StringUtils.isNotNull(saleDeliveryMapper.selectSaleDeliveryById(saleDelivery.getSaleDeliveryId()))) {
            //不存在
            return 0;
        }
        //存在销售订单出库单据
        saleDeliveryMapper.updateSaleDelivery(saleDelivery);//销售订单出库单据
        List<SaleDeliveryListDto> saleDeliveryListOld = saleDeliveryMapper.selectSaleDeliveryListListById(saleDelivery.getSaleDeliveryId());
        List<SaleDeliveryListDomain> saleDeliveryListNew = saleDelivery.getSaleDeliveryLists();//销售订单出库产品信息
//        List<WarehouseListDto> warehouseListDtos = warehouseMapper.selectWarehouseListListById(saleDelivery.getWarehouseId()); // 查询该仓库的产品列表
        for (int i = 0; i < saleDeliveryListNew.size(); i++) {
            SaleDeliveryListDto saleDeliveryListDto = saleDeliveryMapper.selectSaleDeliveryListById(saleDelivery.getSaleDeliveryId(), saleDeliveryListNew.get(i).getProduceId());
            if (StringUtils.isNotNull(saleDeliveryListDto)) {
                for (int j = 0; j < saleDeliveryListOld.size(); j++) {
                    if (saleDeliveryListOld.get(j).getProduceId().equals(saleDeliveryListDto.getProduceId())) {
                        saleDeliveryListOld.remove(j);
                        break;
                    }
                }
                //存在销售订单出库详细
                //更新
//                // 新建仓库子表的对象
//                WarehouseListDomain warehouseListDomain = new WarehouseListDomain();
//                warehouseListDomain.setWarehouseId(saleDelivery.getWarehouseId());
//                warehouseListDomain.setProduceId(saleDeliveryListNew.get(i).getProduceId());
//                for (WarehouseListDto s : warehouseListDtos) {
//                    // 遍历仓库
//                    if (saleDeliveryListNew.get(i).getProduceId().equals(s.getProduceId())) {
//                        // 该产品存在，更新产品数量，产品数量 = 原库存数 + 该产品出库的数量 - 新修改的出库数量
//                        warehouseListDomain.setProductNumber(s.getProductNumber() + saleDeliveryListDto.getSaleDeliveryNumber() - saleDeliveryListNew.get(i).getSaleDeliveryNumber());
//                        break; //终止循环
//                    }
//                }
//                warehouseMapper.updateWarehouseList(warehouseListDomain); // 更新仓库中该产品的数量
                saleDeliveryMapper.updateSaleDeliveryList(saleDeliveryListNew.get(i));
            } else {//新增
                saleDeliveryMapper.insertSaleDeliveryList(saleDeliveryListNew.get(i));
            }
        }
        // 说明有删除的对象
        for (int i = 0; i < saleDeliveryListOld.size(); i++) {
//            // 新建仓库子表的对象
//            WarehouseListDomain warehouseListDomain = new WarehouseListDomain();
//            warehouseListDomain.setWarehouseId(saleDelivery.getWarehouseId());
//            warehouseListDomain.setProduceId(saleDeliveryListOld.get(i).getProduceId());
//            for (WarehouseListDto s : warehouseListDtos) {
//                // 遍历仓库
//                if (saleDeliveryListOld.get(i).getProduceId().equals(s.getProduceId())) {
//                    // 删除时，产品库存数 = 原有库存 + 该产品出库时的库存数
//                    warehouseListDomain.setProductNumber(s.getProductNumber() + saleDeliveryListOld.get(i).getSaleDeliveryNumber());
//                    break; //终止循环
//                }
//            }
//            warehouseMapper.updateWarehouseList(warehouseListDomain); // 更新仓库中该产品的数量
            //最后将要删除的子标记录删除
            saleDeliveryMapper.deleteSaleDeliveryListById(saleDeliveryListOld.get(i).getSaleDeliveryId(), saleDeliveryListOld.get(i).getProduceId());
        }
        return 1;
    }

    /**
     * 销售订单出库
     * app
     *
     * @param saleDelivery
     * @return
     */
    @Override
    public int saleDeliveryStorage(SaleDeliveryDomain saleDelivery) {
        if (!StringUtils.isNotNull(saleDeliveryMapper.selectSaleDeliveryById(saleDelivery.getSaleDeliveryId()))) {
            //不存在
            return 0;
        }
        SaleDeliveryDto saleDeliveryDto = saleDeliveryMapper.selectSaleDeliveryById(saleDelivery.getSaleDeliveryId());//原出库表单数据
        List<SaleDeliveryListDomain> saleDeliveryLists = saleDelivery.getSaleDeliveryLists();//出库单子表信息
        for (int i = 0; i < saleDeliveryLists.size(); i++) {
            // 判断原领料单的子表产品
            boolean existFlag = false;
            for (SaleDeliveryListDomain sl : saleDeliveryLists) {
                if (sl.getProduceId().equals(saleDeliveryLists.get(i).getProduceId())) {
                    existFlag = true;
                    break;
                }
            }
            if (existFlag) {
                //存在
                saleDeliveryMapper.updateSaleDeliveryList(saleDeliveryLists.get(i)); //更新子表
            } else {
                saleDeliveryMapper.insertSaleDeliveryList(saleDeliveryLists.get(i)); //新增子表
            }

            String stockInId = saleDeliveryLists.get(i).getAssociationId();
            StockInRecord stockInRecord = stockInRecordMapper.selectStockInRecordByAssociationId(stockInId); //该子表领料产品的入库记录
            //新增一条出库记录
            StockOutRecord stockOutRecord = new StockOutRecord(stockInRecord.getStockInId(), ERPConstant.SALE_DELIVERY, saleDeliveryDto.getStaffId(), stockInRecord.getProduceId(), stockInRecord.getWarehouseId(), saleDeliveryLists.get(i).getSaleDeliveryNumber());
            stockOutRecordService.insertStockOutRecord(stockOutRecord);
            // 每次子表延迟1s存入数据库
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return 1;
    }

    /**
     * 更新销售订单出库删除标志位
     *
     * @param saleDelivery 销售出库单据
     * @return
     */
    @Override
    public int updateSaleDeliveryDeleteFlag(SaleDeliveryDomain saleDelivery) {
//        List<SaleDeliveryListDomain> saleDeliveryLists = saleDelivery.getSaleDeliveryLists();// 被删除记录的所有子表记录
//        List<WarehouseListDto> warehouseListDtos = warehouseMapper.selectWarehouseListListById(saleDelivery.getWarehouseId()); // 查询该仓库的产品列表
//        for (int i = 0; i < saleDeliveryLists.size(); i++) {
//            // 新建仓库子表的对象
//            WarehouseListDomain warehouseListDomain = new WarehouseListDomain();
//            warehouseListDomain.setWarehouseId(saleDelivery.getWarehouseId());
//            warehouseListDomain.setProduceId(saleDeliveryLists.get(i).getProduceId());
//            for (WarehouseListDto s : warehouseListDtos) {
//                // 遍历仓库
//                if (saleDeliveryLists.get(i).getProduceId().equals(s.getProduceId())) {
//                    // 该产品存在，更新产品数量，产品数量 = 原库存数 + 该产品出库库时增加的数量
//                    warehouseListDomain.setProductNumber(s.getProductNumber() + saleDeliveryLists.get(i).getSaleDeliveryNumber());
//                    break; //终止循环
//                }
//            }
//            warehouseMapper.updateWarehouseList(warehouseListDomain); // 更新仓库中该产品的数量
//        }
        return saleDeliveryMapper.updateSaleDeliveryDeleteFlag(saleDelivery);
    }

    /**
     * 销售订单出库详细查询
     *
     * @return
     */
    @Override
    public List<SaleDeliveryListDto> selectSaleDeliveryListList(SaleDeliveryCond cond) {
        return saleDeliveryMapper.selectSaleDeliveryListList(cond);
    }

    /**
     * 查询销售订单出库对应的所有产品详细
     *
     * @param saleDeliveryId 销售订单出库编号
     * @return
     */
    @Override
    public List<SaleDeliveryListDto> selectSaleDeliveryListListById(String saleDeliveryId) {
        return saleDeliveryMapper.selectSaleDeliveryListListById(saleDeliveryId);
    }

    /**
     * 查询销售订单出库对应的指定产品详细
     *
     * @param saleDeliveryId 销售订单出库编号
     * @param produceId      产品编号
     * @return
     */
    @Override
    public SaleDeliveryListDto selectSaleDeliveryListById(String saleDeliveryId, String produceId) {
        return saleDeliveryMapper.selectSaleDeliveryListById(saleDeliveryId, produceId);
    }

    /**
     * 新增销售出库时，获取销售订单内未出库商品信息
     *
     * @param saleOrderId 销售订单编号
     * @return
     */
    @Override
    public List<SaleDeliveryListDto> getSaleOrderListForDelivery(String saleOrderId) {
        List<SaleOrderListDto> saleOrderListDtos = saleOrderService.selectSaleOrderListListById(saleOrderId);

        List<SaleDeliveryListDto> saleDeliveryListDtoList = new ArrayList<>();
        for (SaleOrderListDto s : saleOrderListDtos) {
            //已出库数<销售数量时，添加
            if (s.getSaleOrderNumber() > s.getSaleDeliveryNumber()) {
                SaleDeliveryListDto saleDeliveryListDto = new SaleDeliveryListDto();
                //相关产品信息添加
                saleDeliveryListDto.setProduceId(s.getProduceId());
                ProductDto productDto = productService.selectProductById(s.getProduceId());
                saleDeliveryListDto.setProduceName(productDto.getProduceName());
                saleDeliveryListDto.setBaseCategoryName(productDto.getBaseCategoryName());
                saleDeliveryListDto.setBaseUnit(productDto.getBaseUnit());
                saleDeliveryListDto.setProduceSpecs(productDto.getProduceSpecs());
                saleDeliveryListDto.setProduceBrand(productDto.getProduceBrand());

                saleDeliveryListDto.setSaleDeliveryUnitPrice(s.getSaleUnitPrice()); //出库单价
                saleDeliveryListDto.setSaleDeliveryNumber(s.getSaleOrderNumber() - s.getSaleDeliveryNumber());
                saleDeliveryListDto.setSaleDeliveryPrice(s.getSaleOrderPrice() - s.getSaleDeliveryPrice());
                saleDeliveryListDtoList.add(saleDeliveryListDto); //添加对象
            }
        }
        return saleDeliveryListDtoList;
    }

    /**
     * 根据销售订单查询销售出库记录
     *
     * @param saleOrderId 销售订单编号
     * @return
     */
    @Override
    public List<SaleDeliveryDto> selectSaleDeliveryBySaleOrderId(String saleOrderId) {
        List<SaleDeliveryDto> saleDeliveryDtos = saleDeliveryMapper.selectSaleDeliveryBySaleOrderId(saleOrderId);
        for (SaleDeliveryDto s : saleDeliveryDtos) {
            double saleDeliveryNumberTotal = 0.00; //出库总数
            double saleDeliveryPriceTotal = 0.00; //出库总价
            if (StringUtils.isNotNull(saleDeliveryMapper.selectSaleDeliveryListListById(s.getSaleDeliveryId()))) {
                //存在，则存入销售订单出库对应产品信息
                List<SaleDeliveryListDto> saleDeliveryListDtos = saleDeliveryMapper.selectSaleDeliveryListListById(s.getSaleDeliveryId());
                for (SaleDeliveryListDto sl : saleDeliveryListDtos) {
                    saleDeliveryNumberTotal += sl.getSaleDeliveryNumber();
                    saleDeliveryPriceTotal += sl.getSaleDeliveryUnitPrice() * sl.getSaleDeliveryNumber();
                }
                s.setSaleDeliveryLists(saleDeliveryListDtos);
            }
            s.setSaleDeliveryNumberTotal(saleDeliveryNumberTotal);
            s.setSaleDeliveryPriceTotal(saleDeliveryPriceTotal);
        }
        return saleDeliveryDtos;
    }
}
